import json
import tarfile

from django.db import connection, router
from django.http import HttpResponse
from django.shortcuts import render

from book.models import Book, Tag


# Create your views here.

#在URL中携带参数
# 1.通过查询字符串(query string):https://www.baidu.com/s?wd=python&a=1&b=2
# 2、在path中携带:http://127.0.0.1:8000/book/2

# 表单参数
# 1.查询字符串:http://127.0.0.1:8000/book?id=3
def book_detail_query_string(request):
    id = request.GET.get('id')
    name = request.GET.get('name')
    return HttpResponse(f"你查找的图书id:{id},图书的名称name:{name}")


# 2、路径传参
def book_detail_path(request,book_id):
    return HttpResponse(f"你查找的图书:{book_id}")



def book_str(request,book_id):
    return HttpResponse(f"你查找的图书id:{book_id}")


def book_slug(request,book_id):
    return HttpResponse(f"你查找的图书id:{book_id}")


def book_uuid(request,book_id):
    return HttpResponse(f"你查找的图书id:{book_id}")


def book_path(request,book_id):
    return HttpResponse(f"你查找的图书id:{book_id}")



def book_detail(request,book_id):
    return HttpResponse(f"你查找的图书id:{book_id}")


def index(request):

    # 获取游标对象
    cursor = connection.cursor()
    # 执行sql
    cursor.execute("select * from book")
    # 获取所有的数据
    rows = cursor.fetchall()
    # 遍历数据
    for row in rows:
        print(row)
    return HttpResponse("获取数据成功")


def add_book(request):
    """
    添加图书
    :param request:
    :return:
    """
    book = Book(name='三国演义', author='罗贯中', price=100)
    # book = Book(name='水浒传', author='施耐庵', price=80)
    book.save()
    return HttpResponse("图书插入成功")



def query_book(request):
    books = Book.objects.all()
    for book in books:
        print(f"{book.name},{book.author},{book.price}")


    # 获取多个记录（filter）
    # books = Book.objects.filter(name='三国演义1')
    # for book in books:
    #     print(f"{book.name},{book.author},{book.price}")


    # 获取单个记录(获取不到会报错),first不会报错
    # try:
        # book = Book.objects.get(name="三国演义11")
        # book = Book.objects.filter(name="三国演义11").first()
    #     print(book)
    #     if book is not None:
    #         print(f"{book.name},{book.author},{book.price}")
    # except Exception as e:
    #     print(f"没有记录 ,{e}")
    return HttpResponse("查找成功!")

def order_book(request):
    books = Book.objects.order_by('price')
    for book in books:
        print(f"{book.name},{book.author},{book.price}")
    return HttpResponse(f'排序成功')



# 修改
def update_book(request):
    book = Book.objects.first()
    book.name = '红楼梦'
    book.save()
    return HttpResponse(f'修改成功')


def delete_book(request):
    book = Book.objects.filter(name='水浒传').delete()
    print(book)
    return HttpResponse(f'删除成功')


def book_tag(request):
    tag = Tag()
    tag.save()
    return HttpResponse('tag插入成功')